package com.jyb.controller;

import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.jfinal.core.Controller;
import com.jyb.config.ConstConfig;
import com.jyb.model.User;
import com.jyb.util.CheckUserUtil;
import com.jyb.util.CqjhMtUtil;
import com.jyb.util.MD5Util;
import com.jyb.util.StringUtils;
import com.jyb.util.UUIDUtils;
import com.jyb.util.ValidateKit;

public class IndexController extends Controller{

	public void index(){
		
		setAttr("mtVos", CqjhMtUtil.getMts());
		setAttr("mtShips", JSON.toJSON(CqjhMtUtil.getMts()));
		
		setAttr("nav", "index");
		renderJsp("/index.jsp");
	}
	
	public void login(){
		
		setAttr("nav", "login");
		renderJsp("/login.jsp");
	}
	
	public void loginout(){
		setCookie(ConstConfig.ACTIVE_USER,"",-1);
		getSession().invalidate();
		setAttr("nav", "login");
		renderJsp("/login.jsp");
	}
	
	public void currentUser(){
		redirect("/");
	}
	
	public void register(){
		
		setAttr("nav", "register");
		renderJsp("/register.jsp");
	}
	
	public void about(){
		
		setAttr("nav", "about");
		renderJsp("/about.jsp");
	}
	
	public void loginAction(){
		
		String cellphone=getPara("cellphone");
		String password=getPara("password");
		User user=User.dao.getUserByCellphoneAndPassword(cellphone, password);
		
		if(user==null){
			setAttr("nav", "login");
			setAttr("msg", "账号或密码错误！");
			renderJsp("/login.jsp");
		}else{
			
			Boolean rememberMe=getParaToBoolean("remember-me");
			if(rememberMe!=null&&rememberMe){
				setCookie(ConstConfig.ACTIVE_USER,CheckUserUtil.encode(cellphone), 60*60*24*7);//七天有效期
			}
			
			getSession().setAttribute("user", User.getUserVo(user));
			redirect("/");
		}
		
	}
	
	public void registerAcrion(){
		
		String cellphone=getPara("cellphone");
		String password=getPara("password");
		
		setAttr("cellphone", cellphone);
		setAttr("password", password);
		
		if(!ValidateKit.isMobile(cellphone)){
			setAttr("nav", "register");
			setAttr("msg", "手机号格式错误！");
			renderJsp("/register.jsp");
		}else if(StringUtils.isEmpty(password)){
			setAttr("nav", "register");
			setAttr("msg", "密码不能为空！");
			renderJsp("/register.jsp");
		}else{
			User userTemp=User.dao.getUserByCellphone(cellphone);
			if(userTemp!=null){
				setAttr("nav", "register");
				setAttr("msg", "该手机号已存在！");
				renderJsp("/register.jsp");
			}else{
				User user=new User();
				user.set("id", UUIDUtils.getUUID());
				user.set("createTime", new Date());
				user.set("cellphone",cellphone);
				user.set("password", MD5Util.MD5(password));
				user.set("nickname", cellphone);
				user.save();
				
				getSession().setAttribute("user", User.getUserVo(user));
				renderJsp("/registerSuccess.jsp");
			}
		}
		
	}
	
	public void findPassword(){
		//String cellphone=getPara("cellphone");
		renderJsp("/registerSuccess.jsp");
	}
	
}
